package com.example.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

public class SampleUtil {
    //阿里云用户的AccessKey ID
    private static final String KEY = "LTAI5tGHfcrJn4NtRnbLrtM2";
    //    阿里云用户的AccessKey Secret
    private static final String SECRET = "UGyJZ28pE9jbJIu8x36lJNh5WhVAf0";
    //    短信签名
    private static final String SignName = "阿里云短信测试";
    //    模板号
    private static final String TemplateCode = "SMS_154950909";

    //    初始化配置
    public static Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID
                .setAccessKeyId(KEY)
                // 配置 AccessKey Secret
                .setAccessKeySecret(SECRET);
        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    //    发验证码
    public static boolean sendMsg(String phone, String code) {
        try {
            Client client = SampleUtil.createClient();
            // 构造请求对象，请替换请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(SignName)
                    .setTemplateCode(TemplateCode)
                    .setTemplateParam("{\"code\":" + code + "}"); // TemplateParam为序列化后的JSON字符串
            // 获取响应对象
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            // 响应包含服务端响应的 body 和 headers
//            System.out.println(toJSONString(sendSmsResponse));
            if ("OK".equals(sendSmsResponse.body.code)) {
                return true;
            } else {
                System.out.println(sendSmsResponse.body.message);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }

//  测试使用
    public static void main(String[] args) throws Exception {
        sendMsg("15965869639", "1234");
    }
}